package com.calvin.study.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;

import cn.hutool.core.lang.Snowflake;

public class ManyTaskTest extends BaseThreadPoolExecutor {

	public static void main(String[] args) {
		try {
			System.out.println("main ... start");
			CompletableFuture<String> future1 = CompletableFuture.supplyAsync(new Supplier<String>() {
				@Override
				public String get() {
					System.out.println("查询商品信息");
					return new Snowflake().nextIdStr() + "_华为M50 Pro";
				}
			}, executor);

			CompletableFuture<String> future2 = CompletableFuture.supplyAsync(new Supplier<String>() {
				@Override
				public String get() {
					try {
						System.out.println("查询商品属性");
					} catch (Exception e) {
						e.printStackTrace();
					}
					return "8G+128G 8G+256G 12G+512G";
				}
			}, executor);

			CompletableFuture<String> future3 = CompletableFuture.supplyAsync(new Supplier<String>() {
				@Override
				public String get() {
					try {
						Thread.sleep(3000);
						System.out.println("查询商品图片");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					return "huaweim50_1.jpg";
				}
			}, executor);

			allOf(future1,future2,future3);
			System.out.println("所有任务执行完成");
			
			//Object obj = anyOf(future1,future2,future3);
			//System.out.println(obj);

			System.out.println("main ... end");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static void allOf(CompletableFuture<?>... cfs) throws InterruptedException, ExecutionException {
		CompletableFuture<Void> allOf = CompletableFuture.allOf(cfs);
		//等待所有异步任务执行完成
		allOf.get();
	}
	
	public static Object anyOf(CompletableFuture<?>... cfs) throws InterruptedException, ExecutionException {
		CompletableFuture<Object> anyOf = CompletableFuture.anyOf(cfs);
		//等待一个异步任务执行完成,即可返回
		return anyOf.get();
	}
}
